#include <fcntl.h>

/* globals to override the load point for the image loader  */
/* the loader centres partial images on the screen
   if the global is set > 39 (and < 80 is implicit) */

/* re: global load co-ordinates
   initially this was developed to use global cords
   for the ProDOS library so when creating the DOS 3.3
   library I left it in for backward compatibility */
char XPIC=0;
char YPIC=0;


/*

When open is used to creat a file under DOS 3.3, param3 is the file's type:

    Param3,hex    File type

    00            Text
    01            Integer basic
    02            Applesoft basic
    04            Binary
    08            Relocatable
    10            S-type file
    20            A-type file
    40            B-type file

*/

extern unsigned HB[];


int piclode(name)
char *name;
{
   int fh,y,y1=0,x1,bos;
   int c = -1, fa = 0, fl = 0;
   int height,packet;
   char tempchar[2];

   fh = open(name,O_RDONLY,4); /* open a binary file */
   if (fh == -1)return -1;

   /* is it a RAG ? */
   c = read(fh,&fa,2);
   if (c == 2)c = read(fh,&fl,2);
   if (c == 2)c = read(fh,tempchar,2);
   if (c == 2) {
   		packet= (int)tempchar[0];
   		height= (int)tempchar[1];
   }
   else {
	   packet = 0;
	   height = 0;
	   fl = 0;
   }

   fa = (packet * height) + 2;
   if (fa != fl) c = -2;
   else {

	   /* center the picture in the screen */
	   if(XPIC>39)
		  x1 = 20-(packet/2); /* break on even byte boundaries */
	   else
		  x1 = (int)XPIC;

	   if((x1%2)!=0)x1--;

	   if(YPIC>191)
		  y1=96-(height/2);
	   else
		  y1=(int)YPIC;

	   bos=y1+height;

	   for(y=y1;y<bos;y++) {
		 c = read(fh,(char *)(HB[y]+x1),packet); /* read each raster to the screen */
		 if (c!=packet)break;
	   }
	   if (c == packet)c = 0;
	   else c = -2;
   }
   close(fh);

   /* zero our globals each time */
   XPIC=0;
   YPIC=0;

   return c;
}
